package com.asiainfo.hybridapp.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.asiainfo.hybridapp.R;
import com.asiainfo.hybridapp.adapter.MeetingDetailAdapter;
import com.asiainfo.hybridapp.configs.ConstantsME;
import com.asiainfo.hybridapp.configs.EventBusTag;
import com.asiainfo.hybridapp.entity.MeetingRankInfo;
import com.framework.application.FrameApplication;
import com.framework.utils.CollectionUtil;
import com.framework.utils.KeyBoardUtil;
import com.framework.utils.PreferencesHelper;
import com.framework.utils.ScreenUtils;
import com.framework2.customLoading.LoadingFooter;
import com.framework2.customLoading.indicators.BallSpinFadeLoaderIndicator;
import com.framework2.customviews.TitleView;
import com.framework2.utils.CustomProgressDialogUtils;
import com.framework2.utils.PicToastUtil;
import com.library.adapter_recyclerview.HorizontalDividerItemDecoration;
import com.library.pulltorefresh.BaseAbstractPullToRefreshLayout;
import com.library.pulltorefresh.classical.SoftClassicalPullToRefreshLayout;
import com.library.pulltorefresh.pullableview.PullableRecyclerView;
import com.library.pulltorefresh.storehouse.LocalDisplay;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import custom.org.greenrobot.eventbus.Subscribe;
import custom.org.greenrobot.eventbus.ThreadMode;

/**
 * 会议列表
 *
 * @author Yangjie
 * className MeetingListActivity
 * created at  2017/3/15  11:30
 */
public class MeetingListActivity extends BaseActivity implements PullableRecyclerView.OnAutoLoadListener {

    @BindView(R.id.titleView)
    TitleView titleView;
    @BindView(R.id.imageView)
    ImageView imageView;
    @BindView(R.id.searchView_et_content)
    EditText searchViewEtContent;
    @BindView(R.id.searchView_iv_search_delete)
    ImageView searchViewIvSearchDelete;
    @BindView(R.id.searchView_go)
    TextView searchViewGo;
    @BindView(R.id.searchView_searchView)
    LinearLayout searchViewSearchView;
    @BindView(R.id.searchView_centerView)
    RelativeLayout searchViewCenterView;
    @BindView(R.id.recyclerView)
    PullableRecyclerView recyclerView;
    @BindView(R.id.refreshView)
    SoftClassicalPullToRefreshLayout refreshLayout;
    @BindView(R.id.recyclerViewSearch)
    PullableRecyclerView recyclerViewSearch;
    @BindView(R.id.refreshViewSearch)
    SoftClassicalPullToRefreshLayout refreshLayoutSearch;
    @BindView(R.id.searchMoveLayout)
    LinearLayout searchMoveLayout;
    private MeetingDetailAdapter adapter;
    private MeetingDetailAdapter searchAdapter;

    private boolean initSearchRecyclerView;
    private List<MeetingRankInfo> meetingRankInfoList = new ArrayList<>();
    private List<MeetingRankInfo> searchList = new ArrayList<>();
    private LoadingFooter footerView;
    private int page = 1;
    private int page_search = 1;
    private int pageSize = 30;
    private String keyWordTemp;
    private String beginDate;
    private String endDate;
    private SimpleDateFormat simpleDateFormat;
    private SimpleDateFormat chooseDateSDF;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_meeting_list);
        ButterKnife.bind(this);
        ScreenUtils.getInstance().setTranslucentStatus(this, true);
        ScreenUtils.getInstance().setStatusBarTintColor(this,
                getResources().getColor(R.color.white));
        initView();
        initDate();
        initPullableRecyclerView();
        initDataRecyclerView();
        initEvent();
        CustomProgressDialogUtils.showProcessDialog(MeetingListActivity.this, "会议列表");
//        test();
        requestMeetingList();
        refreshLayout.autoRefresh(500);
    }

    private void test() {
        for (int i = 0; i < 20; i++) {
            MeetingRankInfo meetingRankInfo = new MeetingRankInfo();
            meetingRankInfo.setTitle("会议排行测试：" + i);
            meetingRankInfo.setCount1(700 + i);
            meetingRankInfo.setCount2(300 + i);
            meetingRankInfo.setCount3(900 + i);
            meetingRankInfo.setDate("2017 06 16");
            meetingRankInfo.setLevelUp(true);
            meetingRankInfoList.add(meetingRankInfo);
            searchList.add(meetingRankInfo);
        }
        CustomProgressDialogUtils.dismissProcessDialog();
        refreshLayout.refreshFinish(BaseAbstractPullToRefreshLayout.SUCCEED);
        refreshLayoutSearch.refreshFinish(BaseAbstractPullToRefreshLayout.SUCCEED);
        adapter.notifyDataSetChanged();
    }

    private void initDate() {
        chooseDateSDF = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -180);
        endDate = chooseDateSDF.format(new Date());
        beginDate = chooseDateSDF.format(calendar.getTime());
    }

    //eventBus通知新消息
    @Subscribe(threadMode = ThreadMode.MAIN, tag = EventBusTag.newMessage)
    public void eventBusNotify(String info) {
    }

    private View initFooter() {
        footerView = new LoadingFooter(this);
        footerView.setLoadingHint("加载更多");
        footerView.setNoMoreHint("到底了");
        footerView.setNoNetWorkHint("网络不给力啊，点击再试一次吧");
        footerView.setState(LoadingFooter.State.Loading);
        footerView.setProgressStyle(BallSpinFadeLoaderIndicator.class);
        return footerView;
    }

    private void initView() {
        titleView.setTitle("具体会议室名称");
    }

    @SuppressWarnings("unchecked")
    private void initDataRecyclerView() {
        //第一种，简单的颜色，高度,水平分割线
//        HorizontalDividerItemDecoration horizontalDividerItemDecoration = new HorizontalDividerItemDecoration
//        (MeetingListActivity.this);
//        horizontalDividerItemDecoration.setColor(this, R.color.white);
//        horizontalDividerItemDecoration.setDividerHeightPx(ScreenUtils.getInstance().dip2px(this, 1));
//        recyclerView.addItemDecoration(horizontalDividerItemDecoration);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        if (CollectionUtil.getInstance().isEmpty(meetingRankInfoList)) {
            showEmptyView("");
        }
        adapter = new MeetingDetailAdapter(this, R.layout.listitem_meeting_detail_rank, meetingRankInfoList);
        recyclerView.setAdapter(adapter);
    }

    private void initPullableRecyclerView() {
        recyclerView.setHasFixedSize(true);
        recyclerView.setCanPullDown(true);
        recyclerView.setCanPullUp(false);
        recyclerView.setHasMoreData(false);
        recyclerView.setOnAutoLoadListener(this);
        refreshLayout.setRefreshContentTextView("会议列表");
        refreshLayout.setLoadContentTextView("会议列表");
        refreshLayout.setEmptyTxt("会议列表为空,点击刷新");
        recyclerViewSearch.setHasFixedSize(true);
        recyclerViewSearch.setCanPullDown(true);
        recyclerViewSearch.setCanPullUp(false);
        recyclerViewSearch.setHasMoreData(false);
        recyclerViewSearch.setOnAutoLoadListener(this);
        refreshLayoutSearch.setRefreshContentTextView("搜索会议");
        refreshLayoutSearch.setLoadContentTextView("搜索会议");
        refreshLayoutSearch.setEmptyTxt("搜索列表为空,点击刷新");
        refreshLayout.setOnRefreshListener(new BaseAbstractPullToRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(final BaseAbstractPullToRefreshLayout pullToRefreshLayout) {
                // 下拉刷新操作
                new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        // 千万别忘了告诉控件刷新完毕了哦！
                        pullToRefreshLayout.refreshFinish(BaseAbstractPullToRefreshLayout.SUCCEED);
                        CustomProgressDialogUtils.showProcessDialog(MeetingListActivity.this, "会议列表");
//                        requestMeetingList();
                        test();
                    }
                }.sendEmptyMessageDelayed(0, 1000);
            }

            @Override
            public void onLoadMore(final BaseAbstractPullToRefreshLayout pullToRefreshLayout) {
                // 加载操作
                new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        // 千万别忘了告诉控件加载完毕了哦！
                        pullToRefreshLayout.loadmoreFinish(BaseAbstractPullToRefreshLayout.SUCCEED);
                        requestMeetingList();
                    }
                }.sendEmptyMessageDelayed(0, 1000);
            }
        });
        refreshLayoutSearch.setOnRefreshListener(new BaseAbstractPullToRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(final BaseAbstractPullToRefreshLayout pullToRefreshLayout) {
                // 下拉刷新操作
                new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        // 千万别忘了告诉控件刷新完毕了哦！
//                        pullToRefreshLayout.refreshFinish(BaseAbstractPullToRefreshLayout.FAIL);
                        requestSaleSearchList(keyWordTemp, "", beginDate, endDate, "");
                    }
                }.sendEmptyMessageDelayed(0, 1500);
            }

            @Override
            public void onLoadMore(final BaseAbstractPullToRefreshLayout pullToRefreshLayout) {
                // 加载操作
                new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        // 千万别忘了告诉控件加载完毕了哦！
//                        pullToRefreshLayout.loadmoreFinish(BaseAbstractPullToRefreshLayout.SUCCEED);
                        requestSaleSearchList(keyWordTemp, "", beginDate, endDate, "");
                    }
                }.sendEmptyMessageDelayed(0, 1000);
            }
        });
    }

    private void initItemDecoration() {
        //第一种，简单的颜色，高度,水平分割线
        HorizontalDividerItemDecoration horizontalDividerItemDecoration =
                new HorizontalDividerItemDecoration(MeetingListActivity.this);
        horizontalDividerItemDecoration.setColor(this, R.color.white);
        horizontalDividerItemDecoration.setDividerHeightPx(ScreenUtils.getInstance().dip2px(this, 10));
        recyclerViewSearch.addItemDecoration(horizontalDividerItemDecoration);
        recyclerViewSearch.setLayoutManager(new LinearLayoutManager(this));
    }

    @SuppressWarnings("unchecked")
    private void initSearchRecyclerView() {
        if (!initSearchRecyclerView) {
            initItemDecoration();
            initSearchRecyclerView = true;
        }
        if (CollectionUtil.getInstance().isEmpty(searchList)) {
            showSearchEmptyView("");
        }
        searchAdapter = new MeetingDetailAdapter(this, R.layout.listitem_meeting_detail_rank, searchList);
        recyclerViewSearch.setAdapter(searchAdapter);
    }

    private void initEvent() {
        searchViewEtContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s)) {
                    if (searchViewIvSearchDelete != null) {
                        searchViewIvSearchDelete.setVisibility(View.VISIBLE);
                    }
                } else if (searchViewIvSearchDelete != null) {
                    searchViewIvSearchDelete.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        searchViewEtContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    if (!TextUtils.isEmpty(v.getText())) {
                        KeyBoardUtil.getInstance().isCloseSoftInputMethod(MeetingListActivity.this,
                                searchViewEtContent, true);
                        requestSearch(v.getText().toString());
                    } else {
                        searchViewEtContent.requestFocus();
                        PicToastUtil.showPicToast(MeetingListActivity.this, "请输入关键字");
                    }
                    return true;
                }
                return false;
            }
        });
    }

    private void onClickSearchButton() {
        try {
            if (!TextUtils.isEmpty(searchViewEtContent.getText())) {
                KeyBoardUtil.getInstance().isCloseSoftInputMethod(MeetingListActivity.this, searchViewEtContent, true);
                requestSearch(searchViewEtContent.getText().toString());
            } else {
                searchViewEtContent.requestFocus();
                PicToastUtil.showPicToast(MeetingListActivity.this, "请输入关键字");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 搜索关键字
     *
     * @param keyWord 关键字
     */
    @SuppressWarnings("unchecked")
    private void requestSearch(@NonNull String keyWord) {
        initSearchRecyclerView();
        requestSaleSearchList(keyWord, "", beginDate, endDate, "");
        keyWordTemp = keyWord;
        recyclerViewSearch.setVisibility(View.VISIBLE);
    }

    private void requestMeetingList() {
        if (TextUtils.isEmpty(PreferencesHelper.getInstance().getStringData(ConstantsME.currentShopId))) {
            FrameApplication.mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    requestMeetingList_("", beginDate, endDate, "");
                }
            }, 100);
        } else {
            requestMeetingList_("", beginDate, endDate, "");
        }
    }

    private void requestMeetingList_(@NonNull final String productType, @NonNull final String beginDate,
                                     @NonNull final String endDate, @NonNull final String outboundType) {
        //用requestSearchSaleList 替换requestSaleList
//        HttpUtil.getInstance().requestSearchSaleList(this, InterfaceConfig.mySalesList, PreferencesHelper
//        .getInstance().getStringData(ConstantsME.currentShopId), "", productType, beginDate, endDate, outboundType,
//        page, pageSize, new HttpUtil.OnRequestListResult<SaleInfo>() {
//            @Override
//            public void onSuccess(List<SaleInfo> list, String... msg) {
//                requestSuccess = true;
//                refreshLayout.refreshFinish(BaseAbstractPullToRefreshLayout.SUCCEED);
//                recyclerView.setOnLoading(false);
//                CustomProgressDialogUtils.dismissProcessDialog();
//                if (!CollectionUtil.getInstance().isEmpty(list)) {
//                    if (page == 1) {
//                        saleInfoList.clear();
//                    }
//                    saleInfoList.addAll(list);
//                    adapter.notifyDataSetChanged();
//                    refreshLayout.resetView();
//                } else if (page == 1 || CollectionUtil.getInstance().isEmpty(list)) {
//                    page = 1;
////                    refreshLayout.showEmptyView();
//                    showEmptyView("暂无销售记录");
//                }
//                try {
//                    String totalCount = msg[0];
//                    int totalCount_ = Integer.parseInt(totalCount);
//                    recyclerView.setHasMoreData(page * pageSize < totalCount_);
//                    if (page * pageSize >= totalCount_) {
//                        if (footerView != null) {
//                            footerView.setState(LoadingFooter.State.NoMore);
//                        }
//                    } else {
//                        if (adapter.getFooterCount() <= 0) {
//                            adapter.addFooterViewAfterSetAdapter(initFooter());
//                        }
//                        page++;
//                    }
//                } catch (Exception e) {
//                    recyclerView.setHasMoreData(false);
//                    if (footerView != null) {
//                        footerView.setState(LoadingFooter.State.NoMore);
//                    }
//                }
//            }
//
//            @Override
//            public void onFail(int code, String msg) {
//                refreshLayout.refreshFinish(BaseAbstractPullToRefreshLayout.FAIL);
//                recyclerView.setOnLoading(false);
//                CustomProgressDialogUtils.dismissProcessDialog();
//                if (page == 1) {
////                    refreshLayout.showEmptyView();
//                    showEmptyView(!TextUtils.isEmpty(msg) && msg.contains("companyId:单位ID不正确") ? "暂无商铺" :
//                    "查询销售记录失败,点击刷新");
//                    saleInfoList.clear();
//                }
//            }
//        });
    }

    private void requestSaleSearchList(String keyWord, @NonNull final String productType,
                                       @NonNull final String beginDate, @NonNull final String endDate,
                                       @NonNull final String outboundType) {
        if (!TextUtils.equals(keyWord, keyWordTemp)) {
            CustomProgressDialogUtils.showProcessDialog(MeetingListActivity.this, "正在搜索");
            page_search = 1;
        }
//        HttpUtil.getInstance().requestSearchSaleList(this, InterfaceConfig.mySalesSearch, PreferencesHelper
//        .getInstance().getStringData(ConstantsME.currentShopId), keyWord, productType, beginDate, endDate,
//        outboundType, page_search, pageSize, new HttpUtil.OnRequestListResult<SaleInfo>() {
//            @Override
//            public void onSuccess(List<SaleInfo> list, String... msg) {
//                refreshLayoutSearch.refreshFinish(CollectionUtil.getInstance().isEmpty(list) ?
//                BaseAbstractPullToRefreshLayout.FAIL : BaseAbstractPullToRefreshLayout.SUCCEED);
//                recyclerViewSearch.setOnLoading(false);
//                CustomProgressDialogUtils.dismissProcessDialog();
//                if (!CollectionUtil.getInstance().isEmpty(list)) {
//                    if (page_search == 1) {
//                        searchList.clear();
//                    }
//                    searchList.addAll(list);
//                    searchAdapter.notifyDataSetChanged();
//                    refreshLayoutSearch.resetView();
//                } else if (page_search == 1 || CollectionUtil.getInstance().isEmpty(searchList)) {
//                    ToastUtil.getInstance().showToast("未检索到有效信息");
//                    page_search = 1;
////                    refreshLayoutSearch.showEmptyView();
//                    showSearchEmptyView("暂无符合筛选条件的数据");
//                }
//                try {
//                    String totalCount = msg[0];
//                    int totalCount_ = Integer.parseInt(totalCount);
//                    recyclerViewSearch.setHasMoreData(page_search * pageSize < totalCount_);
//                    if (page_search * pageSize >= totalCount_) {
//                        if (footerView != null) {
//                            footerView.setState(LoadingFooter.State.NoMore);
//                        }
//                    } else {
//                        if (searchAdapter.getFooterCount() <= 0) {
//                            searchAdapter.addFooterViewAfterSetAdapter(initFooter());
//                        }
//                        page_search++;
//                    }
//                } catch (Exception e) {
//                    recyclerViewSearch.setHasMoreData(false);
//                    if (footerView != null) {
//                        footerView.setState(LoadingFooter.State.NoMore);
//                    }
//                }
//            }
//
//            @Override
//            public void onFail(int code, String msg) {
//                refreshLayoutSearch.refreshFinish(BaseAbstractPullToRefreshLayout.FAIL);
//                recyclerViewSearch.setOnLoading(false);
//                CustomProgressDialogUtils.dismissProcessDialog();
//                if (page_search == 1) {
////                    refreshLayoutSearch.showEmptyView();
//                    showSearchEmptyView(!TextUtils.isEmpty(msg) && msg.contains("companyId:单位ID不正确") ? "暂无商铺" :
//                    "搜索失败,点击刷新");
//                    searchList.clear();
//                }
//            }
//        });
    }

    private void showEmptyView(CharSequence emptyString) {
        View inflate = LayoutInflater.from(MeetingListActivity.this).inflate(R.layout.empty_view, null);
        if (!TextUtils.isEmpty(emptyString)) {
            ((TextView) inflate.findViewById(com.library.pulltorefresh.R.id.tv_empty)).setText(emptyString);
        } else {
            ((TextView) inflate.findViewById(com.library.pulltorefresh.R.id.tv_empty)).setText("");
        }
        inflate.setMinimumWidth(LocalDisplay.getScreenWidthPixels(MeetingListActivity.this));
        inflate.setMinimumHeight(LocalDisplay.getScreenHeightPixels(MeetingListActivity.this));
        refreshLayout.setOnClickEmptyViewListener(refreshLayout);//先设置监听器，再addview
        refreshLayout.setEmptyView(inflate, true);
    }

    private void showSearchEmptyView(CharSequence emptyString) {
        View inflate = LayoutInflater.from(MeetingListActivity.this).inflate(R.layout.empty_view, null);
        if (!TextUtils.isEmpty(emptyString)) {
            ((TextView) inflate.findViewById(com.library.pulltorefresh.R.id.tv_empty)).setText(emptyString);
        } else {
            ((TextView) inflate.findViewById(com.library.pulltorefresh.R.id.tv_empty)).setText("");
        }
        inflate.setMinimumWidth(LocalDisplay.getScreenWidthPixels(MeetingListActivity.this));
        inflate.setMinimumHeight(LocalDisplay.getScreenHeightPixels(MeetingListActivity.this));
        refreshLayoutSearch.setOnClickEmptyViewListener(refreshLayoutSearch);//先设置监听器，再addview
        refreshLayoutSearch.setEmptyView(inflate, true);
    }

    @Override
    public void onAutoLoad(final PullableRecyclerView pullableRecyclerView) {
        pullableRecyclerView.setOnLoading(true);
        new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (pullableRecyclerView.getId() == R.id.recyclerView) {
                    requestMeetingList();
                } else if (pullableRecyclerView.getId() == R.id.recyclerViewSearch) {
                    requestSaleSearchList(keyWordTemp, "", beginDate, endDate, "");
                }
            }
        }.sendEmptyMessageDelayed(0, 100);
    }

    @OnClick({R.id.searchView_iv_search_delete, R.id.searchView_go})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.searchView_iv_search_delete:
                searchViewEtContent.setText("");
                break;
            case R.id.searchView_go:
                onClickSearchButton();
                break;
        }
    }
}
